import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { userApi } from '@/api';
import { authApi } from '@/api/auth';
import type { UserInfo } from '@/api/user';
import axios from 'axios';

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref<UserInfo | null>(null);
  
  // 登录状态
  const isLoggedIn = computed(() => {
    return !!localStorage.getItem('token') && !!userInfo.value;
  });
  
  // 密码登录
  const login = async (data: { username: string, password: string }) => {
    try {
      const response = await authApi.passwordLogin(data);
      
      // 确保 response.token 是一个有效的字符串
      if (response && response.token && typeof response.token === 'string' && response.token.trim() !== '') {
        console.log('登录成功，获取到 token:', response.token);
        localStorage.setItem('token', response.token);
        return response;
      } else {
        console.error('登录响应中没有有效的 token:', response);
        throw new Error('登录失败：服务器未返回有效的认证令牌');
      }
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  };
  
  // 手机号密码登录
  const phoneLogin = async (data: { phone: string, password: string }) => {
    try {
      const response = await authApi.phoneLogin(data);
      localStorage.setItem('token', response.token);
      return response;
    } catch (error) {
      console.error('手机号登录失败:', error);
      throw error;
    }
  };
  
  // 短信验证码登录
  const smsLogin = async (data: { phone: string, sms: string }) => {
    try {
      const response = await authApi.smsLogin(data);
      localStorage.setItem('token', response.token);
      return response;
    } catch (error) {
      console.error('验证码登录失败:', error);
      throw error;
    }
  };
  
  // 注册
  const register = async (data: { phone: string, sms: string, password: string }) => {
    try {
      return await authApi.register(data);
    } catch (error) {
      console.error('注册失败:', error);
      throw error;
    }
  };
  
  // 重置密码
  const resetPassword = async (data: { phone: string, sms: string, newPassword: string }) => {
    try {
      return await authApi.resetPassword(data);
    } catch (error) {
      console.error('重置密码失败:', error);
      throw error;
    }
  };
  
  // 重置token
  const resetToken = () => {
    localStorage.removeItem('token');
    userInfo.value = null;
  };
  
  // 获取用户信息
  const getUserInfo = async (forceRefresh = false) => {
    try {
      // 如果已经有用户信息且不是强制刷新，直接返回
      if (userInfo.value && !forceRefresh) {
        return userInfo.value;
      }
      
      console.log('开始从服务器获取用户信息');
      const response = await userApi.getUserInfo();
      console.log(response,77);
      
      // 确保响应中有数据
      if (response) {
        userInfo.value = response;
        console.log('Store 获取到的用户信息:', userInfo.value);
      } else {
        console.error('获取用户信息响应中没有数据:', response);
        throw new Error('获取用户信息失败：服务器未返回有效数据');
      }
      
      return userInfo.value;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果是 401 错误，可能是 token 过期，清除登录状态
      if (axios.isAxiosError(error) && error.response?.status === 401) {
        logout();
      }
      throw error;
    }
  };
  
  // 更新用户信息
  const updateUserInfo = async (data: Partial<UserInfo>) => {
    try {
      console.log('Store 更新用户信息:', data);
      
      const response = await userApi.updateUserInfo(data);
      
      // 更新本地用户信息
      if (response) {
        // 如果 response 是完整的用户信息对象
        if (response.id) {
          userInfo.value = response;
        } 
        // 如果 response 包含在 data 字段中
        else if (response.data && response.data.id) {
          userInfo.value = response.data;
        }
        // 如果 response 只是部分更新，则合并到现有用户信息中
        else if (userInfo.value) {
          userInfo.value = {
            ...userInfo.value,
            ...data
          };
        }
      }
      
      console.log('更新后的用户信息:', userInfo.value);
      
      return userInfo.value;
    } catch (error) {
      console.error('更新用户信息失败:', error);
      throw error;
    }
  };
  
  // 退出登录
  const logout = () => {
    // 清除 token
    localStorage.removeItem('token');
    // 清除用户信息
    userInfo.value = null;
    // 清除其他可能的缓存
    localStorage.removeItem('userCache');
    sessionStorage.clear();
    // 重置其他状态
    // ...
  };
  
  // 发送短信验证码
  const sendSms = async (phone: string) => {
    try {
      await userApi.sendSms(phone)
      return true
    } catch (error) {
      console.error('发送验证码失败:', error)
      throw error
    }
  }

  // 更新手机号
  const updatePhone = async (data: { phone: string, sms: string }) => {
    try {
      const response = await userApi.updatePhone(data)
      userInfo.value = response.data
      return userInfo.value
    } catch (error) {
      console.error('更新手机号失败:', error)
      throw error
    }
  }

  // 上传头像
  const uploadAvatar = async (file: File) => {
    try {
      return await userApi.uploadAvatar(file)
    } catch (error) {
      console.error('上传头像失败:', error)
      throw error
    }
  }

  // 修改密码
  const changePassword = async (data: { oldPassword: string, newPassword: string }) => {
    try {
      return await userApi.changePassword(data)
    } catch (error) {
      console.error('修改密码失败:', error)
      throw error
    }
  }

  return {
    userInfo,
    isLoggedIn,
    login,
    phoneLogin,
    smsLogin,
    register,
    resetPassword,
    logout,
    getUserInfo,
    updateUserInfo,
    sendSms,
    updatePhone,
    uploadAvatar,
    changePassword,
    resetToken
  };

})
